package com.atguigu.juc.interrupt;

import ch.qos.logback.core.util.TimeUtil;

import java.sql.Time;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Description: 线程中断
 * @author： yeswater
 * @create： 2024/5/29
 */

public class InterruptDemo {
	
	private static volatile boolean isStop = false;
	
	private static AtomicBoolean flag = new AtomicBoolean(false);
	
	public static void main(String[] args) {
		//m1_volatile();
		//m2_atomic();
		
		m3_api();
	}
	
	/* interrupt() + isInterrupted() 中断标志位实现中断 */
	private static void m3_api() {
		Thread thread1 = new Thread(() -> {
			while (true) {
				if (Thread.currentThread().isInterrupted()) {
					System.out.println(Thread.currentThread().getName() + " is stop, 程序停止");
					break;
				}
				System.out.println(Thread.currentThread().getName() + " hello interrupt api");
			}
		}, "thread1");
		thread1.start();
		
		try {
			TimeUnit.MILLISECONDS.sleep(20);
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
		
		Thread thread2 = new Thread(() -> {
			thread1.interrupt();
		}, "thread2");
		thread2.start();
	}
	
	/* AtomicBoolean 实现中断 */
	private static void m2_atomic() {
		new Thread(() -> {
			while (true) {
				if (flag.get()) {
					System.out.println(Thread.currentThread().getName() + " is stop, 程序停止");
					break;
				}
				System.out.println(Thread.currentThread().getName() + " hello atomic");
			}
		}, "thread1").start();
		
		try {
			TimeUnit.MILLISECONDS.sleep(20);
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
		
		new Thread(() -> {
			flag.set(true);
		}, "thread2").start();
	}
	
	/* volatile 实现线程中断 */
	private static void m1_volatile() {
		new Thread(() -> {
			while (true) {
				if (isStop) {
					System.out.println(Thread.currentThread().getName() + " is stop, 程序停止");
					break;
				}
				System.out.println(Thread.currentThread().getName() + " hello volatile");
			}
		}, "thread1").start();
		
		try {
			TimeUnit.MILLISECONDS.sleep(20);
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
		
		new Thread(() -> {
			isStop = true;
		}, "thread2").start();
	}
	
}
